package com.yunti.springboot.config.filter;

/**
 * @author yangtt
 * @date 2023/5/17
 */

import com.yunti.springboot.http.RepeatReadHttpRequest;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author ytt
 * 拦截器httprequest替换 可重复获取inputstream
 */
@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean requestReplaceFilterRegistration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new RequestReplaceFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.setName("RequestReplaceFilter");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    public static class RequestReplaceFilter implements Filter {
        @Override
        public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void destroy() {

        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            filterChain.doFilter(new RepeatReadHttpRequest((HttpServletRequest) servletRequest), servletResponse);
        }
    }
}
